package com.xywang.controller;

import com.xywang.pojo.User;
import com.xywang.service.user.UserService;
import com.xywang.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

@Controller
public class UserLoginController {

    private UserService userServiceImpl;
    @Autowired
    @Qualifier("userServiceImpl")
    public void setUserServiceImpl(UserService userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    @RequestMapping(value = "/login.do",method = RequestMethod.POST)
    public String login(String userCode, String userPassword, HttpSession session, Model model){
        User loginUser = userServiceImpl.login(userCode, userPassword);
        if(loginUser != null){ // loginUser存在，则说明用户密码正确，可以登录
            // 将用户的所有信息放到session中
            session.setAttribute(Constants.USER_SESSION,loginUser);
            System.out.println("用户："+loginUser.getUserName()+" 登录成功！");
            // 跳转主页
            return "redirect:/frame.do";

        }else{// 查无此人，登录失败
            // 转发回登录页面，顺带提示它，用户名或者密码错误；
            model.addAttribute("error","用户名或者密码错误！");
            return "../../login";
        }
    }
    @RequestMapping("/jsp/logout.do")
    public String logoutDo(HttpSession session){
        User user = (User)session.getAttribute(Constants.USER_SESSION);
        session.removeAttribute(Constants.USER_SESSION);
        System.out.println("用户："+user.getUserName()+" 注销成功！");
        return "redirect:/login.jsp";
    }

    @RequestMapping("frame.do")
    public String frame(){
        return "frame";
    }

}
